package com.atguigu.mall.tripartite.util;

import com.atguigu.mall.tripartite.config.CloudStorageConfig;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;

/**
 * @program: Springboot Qiniu
 * @description:
 * @author: CodeDuck
 * @create: 2020-07-30 19:51
 **/
@Service
public class OSSUtil {

    public static String uploadQNImg(FileInputStream file, String key) {
        UploadManager uploadManager = new UploadManager(new Configuration(Zone.autoZone()));
        Auth auth = Auth.create(CloudStorageConfig.QINIU_ACCESS_KEY, CloudStorageConfig.QINIU_SECRET_KEY);
        String token = auth.uploadToken(CloudStorageConfig.QINIU_BUCKET_NAME);
        try{
            // 上传图片文件
            Response res = uploadManager.put(file, key, token, null, null);
            if (!res.isOK()) {
                throw new RuntimeException("上传七牛出错：" + res.toString());
            }
            // 解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(res.bodyString(), DefaultPutRet.class);
            String path = CloudStorageConfig.QINIU_DOMAIN + "/" + putRet.key;
            // 这个returnPath是获得到的外链地址,通过这个地址可以直接打开图片
            return path;
        }catch (QiniuException e){
            e.printStackTrace();
        }
        return "";
    }
}